//
//  UITabBar+PYBadge.m
//  catuncel
//
//  Created by Jim on 2018/1/26.
//  Copyright © 2018年 Jim. All rights reserved.
//

#import "UITabBar+PYBadge.h"

#define TabbarItemNums 5.0    //tabbar的数量

@implementation UITabBar (PYBadge)
//显示小红点
- (void)showBadgeOnItemIndex:(int)index{
    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    
    //新建小红点
    UIView *badgeView = [[UIView alloc]init];
    
    badgeView.tag = 888 + index;
    
    badgeView.layer.cornerRadius = 2.5;//圆形
    
    badgeView.backgroundColor = [UIColor colorWithRed:237.f/255.f green:73.f/255.f blue:86.f/255.f alpha:1];//颜色：红色
    
    CGRect tabFrame = self.frame;
    
    //确定小红点的位置
    float percentX = (index + 0.5) / TabbarItemNums;
    
    CGFloat x = ceilf(percentX * tabFrame.size.width) - 2.5;
    
    CGFloat y = 0;
    
    if (tabFrame.size.height == 49) {
        
        y = ceilf(0.8 * tabFrame.size.height);

    } else {
        
        y = ceilf(0.5 * tabFrame.size.height);
    }
    
    badgeView.frame = CGRectMake(x, y, 5, 5);//圆形大小为5
    
    [self addSubview:badgeView];
}

//隐藏小红点
- (void)hideBadgeOnItemIndex:(int)index {
    
    //移除小红点
    [self removeBadgeOnItemIndex:index];
}

//移除小红点
- (void)removeBadgeOnItemIndex:(int)index{
    
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        
        if (subView.tag == 888 + index) {
            
            [subView removeFromSuperview];
        }
    }
}

@end
